﻿using FrameWorkCore.HangFire.JobConfigs;
using Hangfire;
using Hangfire.SqlServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FrameWorkCore.HangFire
{
    /// <summary>
    /// url/hangfire Open the visual interface
    /// </summary>
    public static class HangFireService
    {
        public static void ConfigureHangFire(this IServiceCollection services, IConfiguration configuration)
        {
           #if !DEBUG
            services.AddHangfire(config => config
                   .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                   .UseSimpleAssemblyNameTypeSerializer()
                   .UseRecommendedSerializerSettings()
                   .UseSqlServerStorage(configuration["HangfireConnection"], new SqlServerStorageOptions
                   {
                       CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                       SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                       QueuePollInterval = TimeSpan.Zero,
                       UseRecommendedIsolationLevel = true,
                       DisableGlobalLocks = true
                   }));

            services.AddHangfireServer();
          #endif
        }
    }

    public static class HangFireAppication
    {

        private static List<string> SchedulingKeys = new List<string>();

        public static void UseHangFireRun(this WebApplication app)
        {
            #if !DEBUG
            app.UseHangfireDashboard();
            app.Lifetime.ApplicationStarted.Register(JobStart);
            app.Lifetime.ApplicationStopped.Register(JobStop);
            #endif
        }


        private static void JobStart()
            => SchedulingKeys.Add(IIsNoRecovery.IIsConfigInit());//Enable a call every 19 minutes a timing task way iis recycled



        private static void JobStop()
        {
            SchedulingKeys.ForEach(key => { RecurringJob.RemoveIfExists("key"); });
            SchedulingKeys = null;
        }
            
    }
}
